
import * as userApi from '@/api/user'
import util from '@/utils/util.js'
// import queryStringify from '@/js_sdk/queryStringify'
import config from '../config.js'
let isCallback = false

function wxLogin(){
	// console.log(this.$route.query)
	let code = ''
	let yq = ''
	try{
		code = this.$route.query.code
		yq = this.$route.query.yq
	}catch(error){
		console.log(65465456)
		code = util.checkgetUrlParam('code')
		yq = util.checkgetUrlParam('yq')
	}

	if(code){
		userApi.authLogin({
			wxapp_id: this.$wxapp_id,
			code,
			yq
		}).then(res => {
			if(res.code == 1){
				uni.setStorageSync("AccessToken",res.data.token)
				uni.removeStorageSync('refresh')
				uni.setStorageSync('wechatCode', code)
				this.userInfo()
			}else if (res.code === 0){
				uni.setStorageSync('wechatCode', code)
			}
		})
	}else{
		util.checkgetCode()
	}
	// // 处理微信回调
	// onCallback()
	// // 跳转到微信授权
	// redirectUrl()
}
function isEmpty(value){
	if (isArray(value)) {
	  return value.length === 0
	}
	if (isObject(value)) {
	  return isEmptyObject(value)
	}
	return !value
}
function isArray (array){
  return Object.prototype.toString.call(array) === '[object Array]'
}
function isObject (object){
  return Object.prototype.toString.call(object) === '[object Object]'
}
function isEmptyObject (object){
  return Object.keys(object).length === 0
}
function urlEncode (obj = {}) {
  const result = []
  for (const key in obj) {
    const item = obj[key]
    if (!item) {
      continue
    }
    if (isArray(item)) {
      item.forEach(val => {
        result.push(key + '=' + val)
      })
    } else {
      result.push(key + '=' + item)
    }
  }
  return result.join('&')
}

 function geturlparam() {
		// window.location.href 获取地址
		let url = window.location.href 
		let p = url.split('?')[1]
		if(p){
			let keyValue = p.split('&');
			let obj = {};
			for (let i = 0; i < keyValue.length; i++) {
				let item = keyValue[i].split('=');
				let key = item[0];
				let value = item[1];
				obj[key] = value;
			}
			return obj
		}

}
// 处理微信回调
function onCallback() {
	
	// 接收微信传来的参数
	const wxParam = queryStringify.parse(window.location.search)
	if (!isEmpty(wxParam)) {
		const url = window.location.href.replace(window.location.search, '')
		window.location.href = url + '?' + urlEncode(wxParam)
		return
	}
	
	// 获取code参数
	const query = geturlparam()
	if (isEmpty(query) || !query.code) {		
		return
	}
	// 请求后端获取微信用户信息
	isCallback = true
	let yq = ""
	userApi.authLogin({
		wxapp_id: config.wxapp_id,
		code:query.code,
		yq
	}).then(res => {
		if(res.code == 1){
			uni.setStorageSync("AccessToken",res.data.token)
			uni.setStorageSync('wechatCode', query.code)
		}else if (res.code === 0){
			uni.setStorageSync('wechatCode', query.code)
		}
	})
}
function redirectUrl() {
	if (isCallback) {
		return
	}
	checkgetCode()
}
// 获取微信授权code（h5）
function checkgetCode(){
	let local = encodeURIComponent(window.location.href);
	let appid =  uni.getStorageSync('appid')
	if(appid){
		window.location.href =
		"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+
		"&redirect_uri=" +
		local +
		"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
	}else{
		userApi.app_wx({
			wxapp_id: config.wxapp_id,
		}).then(res => {
			uni.setStorageSync('appid',res.data)
			window.location.href =
			"https://open.weixin.qq.com/connect/oauth2/authorize?appid="+res.data+
			"&redirect_uri=" +
			local +
			"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
		})
	
	}
}// 获取支付宝授权code（h5）
module.exports = {
	wxLogin:wxLogin
}